package com.xbongbong.pro.message.thread;


import com.alibaba.dingtalk.openapi.newmessage.entity.OA;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.message.constant.PayPlanPushConstant;
import com.xbongbong.pro.message.constant.PaymentPushConstant;
import com.xbongbong.pro.message.enums.PushTimeTypeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.message.model.PushSetModel;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.pushset.PayPlanRemindOverduePushSet;
import com.xbongbong.pro.message.pushset.PayPlanRemindPushSet;
import com.xbongbong.pro.message.pushset.PaymentRemindOverduePushSet;
import com.xbongbong.pro.message.pushset.PaymentRemindPushSet;
import com.xbongbong.pro.message.pushset.SalePushSet;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.message.service.PushService;
import com.xbongbong.saas.constant.TabConstant;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.ReportTargetEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.toolbox.help.BasicHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.TargetLogEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.TargetLogModel;
import com.xbongbong.sys.model.UserModel;
import lombok.Getter;
import lombok.Setter;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 *
 * @author 魏荣杰
 * @date 2019/2/15 17:30
 * @since v1.0
 * @version v1.0
 */
@Setter
@Getter
public class PushDataThread extends Thread {
    private static final Logger LOG = LoggerFactory.getLogger(PushDataThread.class);

    private CompanyModel companyModel;
    private UserModel userModel;
    private PushSetModel pushSetModel;
    private PushModel pushModel;

    private CustomerModel customerModel;
    private PaymentModel paymentModel;
    private ContractUserModel contractUserModel;
    private CompanyConfigModel companyConfigModel;
    private TargetLogModel targetLogModel;
    private PushService pushService;
    private ProBaseConfig proBaseConfig;
    private MessageService messageService;
    private PushHelper pushHelper;
    private EsHelper esHelper;
    private PayPlanModel payPlanModel;
    private PurchaseUserModel purchaseUserModel;
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    private Integer start;
    private Integer pageSize;
    private List<CompanyEntity> companys;

    private IndexTypeModel indexTypeModel;

    public PushDataThread(Integer start, Integer pageSize) {
        this.start = start;
        this.pageSize = pageSize;
    }

    public PushDataThread(List<CompanyEntity> companys) {
        this.companys = companys;
    }

    @Override
    public void run() {
        Integer pageNum = 100;
        if (this.companys != null && this.companys.size() > 0) {
            for (CompanyEntity company : this.companys) {


                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", company.getCorpid()));
                boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(company.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
                SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                CountRequest countRequest = new CountRequest(searchRequest.indices()[0]);
                countRequest.query(searchRequest.source().query());
                long count = 0;
                try {
                    count = xbbElasticsearchRestTemplate.count(countRequest);
                } catch (XbbException e) {
                    LOG.error("com.xbongbong.pro.message.thread.PushDataThread.run count error", e);
//                    Map<String, Object> param = new HashMap<>(16);
//                    param.put("corpid", company.getCorpid());
//                    param.put("del", 0);
//                    count = customerModel.getEntitysCount(param);
                }

                if (count > 2) {
                    //存在客户，客户数小于2的不推送
                    LOG.info("开始计算公司：" + company.getCorpid() + "的简报数据");
                    try {
                        saveCompanyPushDate(company);
                    } catch (XbbException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            Map<String,Object> param = new HashMap<>(16);
            param.put("del", 0);
            //企业授权状态 -1：解除授权 0：禁用 1：正常 2：待激活
            param.put("status", 1);
            //是否接受推送消息,1推送，0不推送
            param.put("isPushMessage", 1);
            param.put("orderByStr", "corpid desc");
            Integer end = this.start + this.pageSize;
            for(; this.start <= end; this.start = this.start + pageNum){
                param.put("start", this.start);
                param.put("pageNum", pageNum);
                this.companys = companyModel.findEntitys(param);
                if (this.companys == null || this.companys.size() == 0) {
                    break;
                }
                for (CompanyEntity company : this.companys) {
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", company.getCorpid()));
                    boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                    IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(company.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
                    SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
                    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                    sourceBuilder.query(boolQueryBuilder);
                    searchRequest.source(sourceBuilder);
                    CountRequest countRequest = new CountRequest(searchRequest.indices()[0]);
                    countRequest.query(searchRequest.source().query());
                    long count = 0;
                    try {
                        count = xbbElasticsearchRestTemplate.count(countRequest);
                    } catch (XbbException e) {
                        LOG.error("com.xbongbong.pro.message.thread.PushDataThread.run count error", e);
//                        //存在客户的才进入计算,先根据corpid计算客户数
//                        Map<String,Object> param2 = new HashMap<>(16);
//                        param2.put("corpid", company.getCorpid());
//                        param2.put("del", 0);
//                        count = customerModel.getEntitysCount(param2);
                    }

                    if(count > 2 ){
                        //存在客户，客户数小于2的不推送
                        LOG.info("开始计算公司：" + company.getCorpid() + "的简报数据");
                        try {
                            saveCompanyPushDate(company);
                        } catch (Exception e){
                            LOG.error("oh, i outcrop the error! corpid:" + company.getCorpid(), e);
                        }
                    }
                }
            }
        }
    }

    /**
     * 保存公司的推送信息
     *
     * @param company 公司
     * @since 3.11
     * @author 焕勇
     * 创建时间：很久以前
     * 修改时间：2017-8-11 下午2:41:12 by zcp
     * 此次主要改了销售简报推送
     */
    private void saveCompanyPushDate(CompanyEntity company) throws XbbException {

        String corpid = company.getCorpid();
        //获取推送规则
        SalePushSet salePushSet = new SalePushSet();
        PushSetEntity salePushSetEntity = salePushSet.getPushSet(corpid, PushTypeEnum.SALE_REPORT_PUSH.getSubCode(), pushSetModel);

        PaymentRemindPushSet paymentRemindPushSet = new PaymentRemindPushSet();
        PushSetEntity paymentRemindPushSetEntity = paymentRemindPushSet.getPushSet(corpid, PushTypeEnum.PAYMENT_REMIND.getSubCode(), pushSetModel);

        PaymentRemindOverduePushSet paymentRemindOverduePushSet = new PaymentRemindOverduePushSet();
        PushSetEntity paymentOverduePushSetEntity = paymentRemindOverduePushSet.getPushSet(corpid, PushTypeEnum.PAYMENT_OVERDUE.getSubCode(), pushSetModel);

        PayPlanRemindPushSet payPlanRemindPushSet = new PayPlanRemindPushSet();
        PushSetEntity payPlanRemindPushSetEntity = payPlanRemindPushSet.getPushSet(corpid, PushTypeEnum.PAY_PLAN_REMIND.getSubCode(), pushSetModel);

        PayPlanRemindOverduePushSet payPlanRemindOverduePushSet = new PayPlanRemindOverduePushSet();
        PushSetEntity payPlanOverduePushSetEntity = payPlanRemindOverduePushSet.getPushSet(corpid,PushTypeEnum.PAY_PLAN_OVERDUE.getSubCode(),pushSetModel);

        //不启用则不提醒
        boolean salePushSetEnable = (salePushSetEntity == null || Objects.equals(salePushSetEntity.getEnable(), 0));
        boolean paymentRemindPushSetEnable = (paymentRemindPushSetEntity == null || Objects.equals(paymentRemindPushSetEntity.getEnable(), 0));
        boolean paymentOverduePushSetEnable = (paymentOverduePushSetEntity == null || Objects.equals(paymentOverduePushSetEntity.getEnable(), 0));
        boolean payPlanRemindPushSetEnable = (payPlanRemindPushSetEntity == null || Objects.equals(payPlanRemindPushSetEntity.getEnable(), 0));
        boolean payPlanOverduePushSetEnable = (payPlanOverduePushSetEntity == null || Objects.equals(payPlanOverduePushSetEntity.getEnable(), 0));
        if(salePushSetEnable && paymentRemindPushSetEnable && paymentOverduePushSetEnable && payPlanRemindPushSetEnable && payPlanOverduePushSetEnable){
            return;
        }

        //推送的userId和时间
        List<String> salePushUserIdList = null;
        Long salePushTime = 0L;
        UserEntity corpUser = new UserEntity();
        corpUser.setCorpid(corpid);
        if(salePushSetEntity != null && salePushSetEntity.getEnable().equals(1)){

            //销售简报的规则有角色、部门、自定义接收人
            salePushUserIdList = pushHelper.getPushUserIdList(corpUser, salePushSetEntity.getPushObject(),null,null);

            JSONObject pushTimeObject = JSONObject.parseObject(salePushSetEntity.getPushTime());
            salePushTime = pushTimeObject.getLong("time") == null ? 28800 : pushTimeObject.getLong("time");
        }

        List<String> paymentRemindPushUserIdList = null;
        Long paymentRemindPushTime = 0L;
        if(paymentRemindPushSetEntity != null && paymentRemindPushSetEntity.getEnable().equals(1)) {
            paymentRemindPushUserIdList = pushHelper.getPushUserIdList(corpUser, paymentRemindPushSetEntity.getPushObject(), null, null);
            JSONObject pushTimeObject = JSONObject.parseObject(paymentRemindPushSetEntity.getPushTime());
            paymentRemindPushTime = pushTimeObject.getLong("time") == null ? 28800 : pushTimeObject.getLong("time");
        }

        List<String> paymentOverduePushUserIdList= new ArrayList<>();
        Long paymentOverduePushTime = DateTimeUtil.getTodayInt();
        Long paymentOverdueBusTime = paymentOverduePushTime;
        if (paymentOverduePushSetEntity != null && paymentOverduePushSetEntity.getEnable().equals(1)) {
            paymentOverduePushUserIdList = pushHelper.getPushUserIdList(corpUser, paymentOverduePushSetEntity.getPushObject(), null, null);
            JSONObject pushTimeObject = JsonHelperUtil.parseObject(paymentOverduePushSetEntity.getPushTime());
            Integer period = pushTimeObject.getInteger("period");
            Integer timeType = pushTimeObject.getInteger("timeType");
            if (Objects.equals(timeType, PushTimeTypeEnum.DELAYED.getCode())) {
                paymentOverdueBusTime = paymentOverduePushTime - period;
            }
            //早上8点
            paymentOverduePushTime += 28800;
        }
        //付款计划未付款提醒
        List<String> payPlanRemindPushUserIdList = null;
        Long payPlanRemindPushTime = 0L;
        if(payPlanRemindPushSetEntity != null && payPlanRemindPushSetEntity.getEnable().equals(1)) {
            payPlanRemindPushUserIdList = pushHelper.getPushUserIdList(corpUser, payPlanRemindPushSetEntity.getPushObject(), null, null);
            JSONObject pushTimeObject = JSONObject.parseObject(payPlanRemindPushSetEntity.getPushTime());
            payPlanRemindPushTime = pushTimeObject.getLong("time") == null ? 28800 : pushTimeObject.getLong("time");
        }
        //付款计划逾期提醒
        List<String> payPlanOverduePushUserIdList= new ArrayList<>();
        Long payPlanOverduePushTime = DateTimeUtil.getTodayInt();
        Long payPlanOverdueBusTime = payPlanOverduePushTime;
        if (payPlanOverduePushSetEntity != null && payPlanOverduePushSetEntity.getEnable().equals(1)) {
            payPlanOverduePushUserIdList = pushHelper.getPushUserIdList(corpUser, payPlanOverduePushSetEntity.getPushObject(), null, null);
            JSONObject pushTimeObject = JsonHelperUtil.parseObject(payPlanOverduePushSetEntity.getPushTime());
            Integer period = pushTimeObject.getInteger("period");
            Integer timeType = pushTimeObject.getInteger("timeType");
            if (Objects.equals(timeType, PushTimeTypeEnum.DELAYED.getCode())) {
                payPlanOverdueBusTime = payPlanOverduePushTime - period;
            }
            //早上8点
            payPlanOverduePushTime += 28800;
        }

        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", company.getCorpid());
        param.put("del", 0);
        //是否接受推送消息,1推送，0不推送
        param.put("isPushMessage", 1);
//		//开始位置
//		Integer start = 0;
        //一页500
        Integer pagerNum = 100;
        //总页数
        Integer pageTotal;
        Integer userCount = userModel.getEntitysCount(param);
        pageTotal = userCount / pagerNum;
        //不能整除，页码加1
        if(userCount % pagerNum > 0){
            pageTotal = pageTotal + 1;
        }
		/*
		 * 注，计算指标一般都是在凌晨对上一天的数据进行统计，固对于统计日（或周）的开始截至时间即上一天的开始截止
		 * （1）正常情况，当天早上统计昨日数据，时间范围：dayStart--dayEnd				同时统计dayEnd-86400所在月份的数据
		 * （2）今日是周一的时候，统计上一周的数据，时间范围：weekStart--weekEnd			同时统计weekEnd-96400所在月份的数据
		 */
        Integer timeType = BasicHelper.getTimeType(DateUtil.getInt());
        Map<String, Integer> ret = BasicHelper.getDayStartAndEnd4Report(timeType);
        Integer dayStartTime = ret.get("start");
        Integer dayEndTime = ret.get("end");
        for(int page = 1 ; page < pageTotal + 1 ; page++){
            Integer start = (page - 1) * pagerNum;
            param.put("start", start);
            param.put("pageNum", pagerNum);
            List<UserEntity> users = userModel.findEntitys(param);
            for (UserEntity user : users) {
                //遍历公司所有人
                saveUserPushDate(user, salePushUserIdList, salePushTime, paymentRemindPushUserIdList, paymentRemindPushTime, dayStartTime.longValue(), dayEndTime.longValue(), paymentOverduePushUserIdList, paymentOverduePushTime, paymentOverdueBusTime,payPlanRemindPushUserIdList,payPlanRemindPushTime,payPlanOverduePushUserIdList,payPlanOverduePushTime,payPlanOverdueBusTime);
            }
        }
    }

    /**
     * 保存某个用户的推送信息
     *  @param userEntity 公司员工
     * @param salePushUserIdList 推送的userId
     * @param salePushTime 推送时间
     * @param paymentRemindPushUserIdList 提醒用户ID列表
     * @param paymentRemindPushTime 提示时间
     * @param dayStartTime 统计日开始时间--销售简报
     * @param dayEndTime 统计日结束时间--销售简报    @since 很久以前
     * @param paymentOverduePushUserIdList 逾期回款提醒用户id
     * @param paymentOverduePushTime   逾期回款提醒时间
     * @param paymentOverdueBusTime  逾期回款查询时间
     * @param payPlanRemindPushUserIdList 未付款计划提醒用户ID列表
     * @param payPlanRemindPushTime 未付款计划提示时间
     * @param payPlanOverduePushUserIdList 逾期未付款提醒用户id
     * @param payPlanOverduePushTime 逾期付款提醒时间
     * @param payPlanOverdueBusTime 逾期付款查询时间
     * @author 焕勇
     * 创建时间：很久以前
     * 修改时间：2017-8-11 下午2:42:33
     * 此次主要改了销售简报推送
     */
    private void saveUserPushDate(UserEntity userEntity, List<String> salePushUserIdList, Long salePushTime, List<String> paymentRemindPushUserIdList, Long paymentRemindPushTime, Long dayStartTime, Long dayEndTime, List<String> paymentOverduePushUserIdList, Long paymentOverduePushTime, Long paymentOverdueBusTime, List<String> payPlanRemindPushUserIdList, Long payPlanRemindPushTime,List<String> payPlanOverduePushUserIdList,Long payPlanOverduePushTime,Long payPlanOverdueBusTime) throws XbbException {
        //销售简报数据计算，暂时只给老板或超级管理员发（数据权限为全公司5的用户）
        //if(userModel.isLeaderOrBoss(userEntity)){
        if(salePushUserIdList != null && salePushUserIdList.contains(userEntity.getUserId())){
            saveSalesPresentations(userEntity, salePushTime, dayStartTime, dayEndTime);
        }
        //应收款提醒计算
        if(paymentRemindPushUserIdList != null && paymentRemindPushUserIdList.contains(userEntity.getUserId())){
            savePaymentReminder(userEntity, paymentRemindPushTime);
        }
        if (paymentOverduePushUserIdList != null && paymentOverduePushUserIdList.contains(userEntity.getUserId())) {
            savePaymentOverdue(userEntity, paymentOverdueBusTime, paymentOverduePushTime);
        }
        if ( payPlanRemindPushUserIdList !=null && payPlanRemindPushUserIdList.contains(userEntity.getUserId()) ){
            savePayPlanReminder(userEntity, payPlanRemindPushTime);
        }
        if (payPlanOverduePushUserIdList != null && payPlanOverduePushUserIdList.contains(userEntity.getUserId())) {
            savePayPlanOverdue(userEntity, payPlanOverdueBusTime, payPlanOverduePushTime);
        }
    }


    /**
     * 保存用户的回款提醒推送
     * @param userEntity 用户对象
     */
    private void savePayPlanReminder(UserEntity userEntity, Long pushTime) throws XbbException {
        pushTime = getPushTime(pushTime);

        JSONObject dataJson = getPayPlanReminder(userEntity);
        if(dataJson == null){
            return ;
        }

        List<String> userIdList = new ArrayList<>();
        userIdList.add(userEntity.getUserId());

        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO();
        messageRabbitMqDTO.setCorpid(userEntity.getCorpid());
        messageRabbitMqDTO.setUserIds(userIdList);
        messageRabbitMqDTO.setRefIds(Collections.singletonList(0L));
        messageRabbitMqDTO.setRemind(0);
        messageRabbitMqDTO.setPushTime(pushTime);
        messageRabbitMqDTO.setTitle(dataJson.getString("title"));
        messageRabbitMqDTO.setContent(dataJson.getString("content"));
        messageRabbitMqDTO.setForm(null);

        PushRefTypePojo.Options options = new PushRefTypePojo.Options();
        options.setAppId(dataJson.getLong("appId"));
        options.setMenuId(dataJson.getLong("menuId"));
        options.setSaasMark(SaasMarkEnum.SAAS.getCode());
        options.setSubBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
        options.setDataIds(JSONArray.parseArray(dataJson.getString("dataIds"), Long.class));
        messageRabbitMqDTO.setOptions(options);

        messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.PAY_PLAN_REMIND);
    }

    private JSONObject getPayPlanReminder(UserEntity userEntity) {
        Map<String,Object> param = new HashMap<>(16);
        String corpid = userEntity.getCorpid();

        //获取主负责人的采购合同ID//只算自己的付款
        List<String> userIdIn = new ArrayList<>();
        userIdIn.add(userEntity.getUserId());

        param.put("corpid", corpid);
        param.put("del", 0);
        //采购合同主负责人
        param.put("isMain", 1);
        param.put("userIdIn", userIdIn);

        List<PurchaseUserEntity> purchaseUserList = purchaseUserModel.findEntitys(param);

        Set<Long> purchaseIdIn = new HashSet<>();
        for (PurchaseUserEntity entity : purchaseUserList) {
            purchaseIdIn.add(entity.getDataId());
        }
        List<PayPlanEntityExt> payPlantList;
        try {
            Integer nowTime = DateUtil.getTodayInt();
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                    .filter(termsQuery("data." + PayPlanEnum.STATUS.getAttr(), Arrays.asList(PayPlanStatusEnum.UN_RECEIVABLES.getCode(), PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode())))
                    .filter(termsQuery("data." + PayPlanEnum.LINK_PURCHASE.getAttr(), purchaseIdIn))
                    .filter(rangeQuery("data." + PayPlanEnum.ESTIMATE_TIME.getAttr()).gte(nowTime).lt(nowTime + 7 * 86400));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAY_PLAN, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            param.clear();
            param.put("corpid", corpid);
            param.put("del", 0);
            param.put("idIn", ids);
            payPlantList = payPlanModel.findEntitys(param);

        } catch (Exception e) {
            Long startTime = DateTimeUtil.getTodayInt();
            Long endTime = startTime + 7 * 86400;
            payPlantList = payPlanModel.getPayPlanRemindByPurchaseId(corpid, new ArrayList<>(purchaseIdIn), startTime, endTime);
        }

        Integer unPayPlanCount = payPlantList.size();
        long appId = 0;
        long menuId = 0;
        List<Long> ids = new ArrayList<>();
        //未回款金额
        Double unPayPlanMoney = 0.0;
        for(PayPlanEntityExt payPlanEntity : payPlantList){
            if(payPlanEntity != null){
                JSONObject paymentObject = payPlanEntity.getData();
                if (paymentObject != null) {
                    if (paymentObject.getDouble(PayPlanEnum.UN_AMOUNT.getAttr()) != null) {
                        unPayPlanMoney += paymentObject.getDouble(PayPlanEnum.UN_AMOUNT.getAttr());
                    }
                    appId = payPlanEntity.getAppId();
                    menuId = payPlanEntity.getMenuId();
                    ids.add(payPlanEntity.getId());
                }
            }
        }
        JSONObject jsonObject = null;
        if(unPayPlanCount > 0){
            //没有回款信息不推送
            unPayPlanMoney = (unPayPlanMoney < 0) ? 0 : unPayPlanMoney;

            jsonObject = new JSONObject();
            jsonObject.put("content", String.format(I18nMessageUtil.getMessage(I18nStringConstant.PAY_REMIND_CONTENT),unPayPlanCount,unPayPlanMoney));
            jsonObject.put("title", String.format(I18nMessageUtil.getMessage(I18nStringConstant.ACCOUNT_PAYABLE_DAY), 7));
            jsonObject.put("appId", appId);
            jsonObject.put("menuId", menuId);
            jsonObject.put("dataIds", ids);
        }
        return jsonObject;
    }

    /**
     * Description: 逾期付款消息入库
     * @param userEntity 用户
     * @param payPlanOverdueBusTime 查询时间
     * @param payPlanOverduePushTime 推送时间
     * @author 魏荣杰
     * @date 2018/8/31 18:40
     * @since v3.28
     * Modified by:
     */
    private void savePayPlanOverdue(UserEntity userEntity, Long payPlanOverdueBusTime, Long payPlanOverduePushTime) throws XbbException {
        JSONObject dataJson = getPayPlanOverdue(userEntity, payPlanOverdueBusTime);
        if (dataJson == null) {
            return;
        }

        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO();
        messageRabbitMqDTO.setCorpid(userEntity.getCorpid());
        messageRabbitMqDTO.setUserIds(Collections.singletonList(userEntity.getUserId()));
        messageRabbitMqDTO.setRefIds(Collections.singletonList(0L));
        messageRabbitMqDTO.setRemind(0);
        messageRabbitMqDTO.setPushTime(payPlanOverduePushTime);
        messageRabbitMqDTO.setTitle(dataJson.getString("title"));
        messageRabbitMqDTO.setContent(dataJson.getString("content"));
        messageRabbitMqDTO.setForm(null);

        PushRefTypePojo.Options options = new PushRefTypePojo.Options();
        options.setAppId(dataJson.getLong("appId"));
        options.setMenuId(dataJson.getLong("menuId"));
        options.setSaasMark(SaasMarkEnum.SAAS.getCode());
        options.setSubBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
        options.setDataIds(JSONArray.parseArray(dataJson.getString("dataIds"), Long.class));
        messageRabbitMqDTO.setOptions(options);

        messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.PAY_PLAN_OVERDUE);
    }

    private JSONObject getPayPlanOverdue(UserEntity userEntity, Long payPlanOverdueBusTime) {
        String corpid = userEntity.getCorpid();
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("isMain", 1);
        param.put("userId", userEntity.getUserId());
        List<PurchaseUserEntity> purchaseUserEntityList = purchaseUserModel.findEntitys(param);

        Set<Long> purchaseIds = new HashSet<>();
        for (PurchaseUserEntity entity : purchaseUserEntityList) {
            purchaseIds.add(entity.getDataId());
        }
        List<PayPlanEntityExt> payPlanEntityList;
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                    .filter(termsQuery("data." + PayPlanEnum.STATUS.getAttr(), Arrays.asList(PayPlanStatusEnum.UN_RECEIVABLES.getCode(), PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode())))
                    .filter(termsQuery("data." + PayPlanEnum.LINK_PURCHASE.getAttr(), purchaseIds))
                    .filter(rangeQuery("data." + PayPlanEnum.ESTIMATE_TIME.getAttr()).gte(payPlanOverdueBusTime).lt(payPlanOverdueBusTime + 86400));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAY_PLAN, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            param.clear();
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            payPlanEntityList = payPlanModel.findEntitys(param);
        } catch (Exception e) {
            //es 出错转数据库
            payPlanEntityList = payPlanModel.getPayPlanOverdueByPurchaseId(corpid, new ArrayList<>(purchaseIds), payPlanOverdueBusTime, payPlanOverdueBusTime + 86400);
        }

        long appId = 0;
        long menuId = 0;
        List<Long> ids = new ArrayList<>();
        Integer unPayPlanCount = payPlanEntityList.size();
        Double unPayPlanMoney = 0D;
        for (PayPlanEntityExt entity : payPlanEntityList) {
            JSONObject payPlanDataObject = entity.getData();
            if (payPlanDataObject != null) {
                if (payPlanDataObject.getDouble(PayPlanEnum.UN_AMOUNT.getAttr()) != null) {
                    unPayPlanMoney += payPlanDataObject.getDouble(PayPlanEnum.UN_AMOUNT.getAttr());
                }
                appId = entity.getAppId();
                menuId = entity.getMenuId();
                ids.add(entity.getId());
            }
        }

        JSONObject jsonObject = null;
        if (unPayPlanCount > 0) {
            unPayPlanMoney = (unPayPlanMoney < 0) ? 0 :unPayPlanMoney;
            jsonObject = new JSONObject();
            jsonObject.put("content", String.format(I18nMessageUtil.getMessage(PayPlanPushConstant.PAY_PLAN_OVERDUE_CONTENT), unPayPlanCount, unPayPlanMoney));
            jsonObject.put("title", I18nMessageUtil.getMessage(PayPlanPushConstant.PAY_PLAN_OVERDUE_TITLE));
            jsonObject.put("appId", appId);
            jsonObject.put("menuId", menuId);
            jsonObject.put("dataIds", ids);
        }
        return jsonObject;
    }


    /**
     * Description: 逾期回款消息入库
     * @param userEntity 用户
     * @param paymentOverdueBusTime 查询时间
     * @param paymentOverduePushTime 推送时间
     * @author 魏荣杰
     * @date 2018/8/31 18:40
     * @since v3.28
     * Modified by:
     */
    private void savePaymentOverdue(UserEntity userEntity, Long paymentOverdueBusTime, Long paymentOverduePushTime) throws XbbException {
        JSONObject dataJson = getPaymentOverdue(userEntity, paymentOverdueBusTime);
        if (dataJson == null) {
            return;
        }

        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO();
        messageRabbitMqDTO.setCorpid(userEntity.getCorpid());
        messageRabbitMqDTO.setUserIds(Collections.singletonList(userEntity.getUserId()));
        messageRabbitMqDTO.setRefIds(Collections.singletonList(0L));
        messageRabbitMqDTO.setRemind(0);
        messageRabbitMqDTO.setPushTime(paymentOverduePushTime);
        messageRabbitMqDTO.setTitle(dataJson.getString("title"));
        messageRabbitMqDTO.setContent(dataJson.getString("content"));
        messageRabbitMqDTO.setForm(null);

        PushRefTypePojo.Options options = new PushRefTypePojo.Options();
        options.setAppId(dataJson.getLong("appId"));
        options.setMenuId(dataJson.getLong("menuId"));
        options.setSaasMark(SaasMarkEnum.SAAS.getCode());
        options.setSubBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
        options.setDataIds(JSONArray.parseArray(dataJson.getString("dataIds"), Long.class));
        messageRabbitMqDTO.setOptions(options);

        messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.PAYMENT_OVERDUE);

/*        PushEntity pushEntity = new PushEntity();
        pushEntity.setAttrEntity("");
        pushEntity.setCorpid(userEntity.getCorpid());
        pushEntity.setId(null);
        pushEntity.setIsPush(0);
        pushEntity.setMsg(dataJson.toJSONString());
        pushEntity.setPushObject(JSONObject.toJSONString(Collections.singleton(userEntity.getUserId())));
        pushEntity.setPushTime(paymentOverduePushTime);
        pushEntity.setRefEntity(RefEntityEnum.PAYMENT_SHEET.getCode());
        pushEntity.setRefId(0L);
        pushEntity.setSubType(PushTypeEnum.PAYMENT_OVERDUE.getSubCode());
        pushEntity.setType(PushTypeEnum.PAYMENT_OVERDUE.getCode());

        pushService.save(pushEntity);*/
    }

    private JSONObject getPaymentOverdue(UserEntity userEntity, Long paymentOverdueBusTime) {
        String corpid = userEntity.getCorpid();
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("isMain", 1);
        param.put("userId", userEntity.getUserId());
        List<ContractUserEntity> contractUserEntityList = contractUserModel.findEntitys(param);

        Set<Long> contractIds = new HashSet<>();
        for (ContractUserEntity entity : contractUserEntityList) {
            contractIds.add(entity.getDataId());
        }
        List<PaymentEntityExt> paymentEntityList;
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                    .filter(termsQuery("data." + PaymentEnum.STATUS.getAttr(), Arrays.asList(PaymentStatusEnum.UN_RECEIVABLES.getCode(), PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())))
                    .filter(termsQuery("data." + PaymentEnum.CONTRACT.getAttr(), contractIds))
                    .filter(rangeQuery("data." + PaymentEnum.ESTIMATE_TIME.getAttr()).gte(paymentOverdueBusTime).lt(paymentOverdueBusTime + 86400));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            param.clear();
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            paymentEntityList = paymentModel.findEntitys(param);
        } catch (Exception e) {
            //es 出错转数据库
            paymentEntityList = paymentModel.getPaymentOverdueByContractId(corpid, new ArrayList<>(contractIds), paymentOverdueBusTime, paymentOverdueBusTime + 86400);
        }

        long appId = 0;
        long menuId = 0;
        List<Long> ids = new ArrayList<>();
        Integer unPaymentCount = paymentEntityList.size();
        Double unPaymentMoney = 0D;
        for (PaymentEntityExt entity : paymentEntityList) {
            JSONObject paymentDataObject = entity.getData();
            if (paymentDataObject != null) {
                if (paymentDataObject.getDouble(PaymentEnum.UN_AMOUNT.getAttr()) != null) {
                    unPaymentMoney += paymentDataObject.getDouble(PaymentEnum.UN_AMOUNT.getAttr());
                }
                appId = entity.getAppId();
                menuId = entity.getMenuId();
                ids.add(entity.getId());
            }
        }

        JSONObject jsonObject = null;
        if (unPaymentCount > 0) {
            unPaymentMoney = (unPaymentMoney < 0) ? 0 :unPaymentMoney;
            jsonObject = new JSONObject();
            jsonObject.put("content", String.format(I18nMessageUtil.getMessage(PaymentPushConstant.PAYMENT_OVERDUE_CONTENT), unPaymentCount, unPaymentMoney));
            jsonObject.put("title", I18nMessageUtil.getMessage(PaymentPushConstant.PAYMENT_OVERDUE_TITLE));
            jsonObject.put("appId", appId);
            jsonObject.put("menuId", menuId);
            jsonObject.put("dataIds", ids);

//            jsonObject.put("text", "销帮帮CRM逾期收款提醒");
//            String messageUrl = proBaseConfig.getProjectDingtalkUrl() + String.format(DingtalkPageUrlEnum.PAYMENT_LIST.getUrl(), "");
//            jsonObject.put("messageUrl", messageUrl);
        }
        return jsonObject;
    }

    /**
     * 保存用户的回款提醒推送
     * @param userEntity 用户对象
     */
    private void savePaymentReminder(UserEntity userEntity, Long pushTime) throws XbbException {
        pushTime = getPushTime(pushTime);

        JSONObject dataJson = getPaymentReminder(userEntity);
        if(dataJson == null){
            return ;
        }

        List<String> userIdList = new ArrayList<>();
        userIdList.add(userEntity.getUserId());

        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO();
        messageRabbitMqDTO.setCorpid(userEntity.getCorpid());
        messageRabbitMqDTO.setUserIds(userIdList);
        messageRabbitMqDTO.setRefIds(Collections.singletonList(0L));
        messageRabbitMqDTO.setRemind(0);
        messageRabbitMqDTO.setPushTime(pushTime);
        messageRabbitMqDTO.setTitle(dataJson.getString("title"));
        messageRabbitMqDTO.setContent(dataJson.getString("content"));
        messageRabbitMqDTO.setForm(null);

        PushRefTypePojo.Options options = new PushRefTypePojo.Options();
        options.setAppId(dataJson.getLong("appId"));
        options.setMenuId(dataJson.getLong("menuId"));
        options.setSaasMark(SaasMarkEnum.SAAS.getCode());
        options.setSubBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
        options.setDataIds(JSONArray.parseArray(dataJson.getString("dataIds"), Long.class));
        messageRabbitMqDTO.setOptions(options);

        messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.PAYMENT_REMIND);

    }

    private JSONObject getPaymentReminder(UserEntity userEntity) {
        Map<String,Object> param = new HashMap<>(16);
        String corpid = userEntity.getCorpid();

        //获取主负责人的合同ID//只算自己的回款
        List<String> userIdIn = new ArrayList<>();
        userIdIn.add(userEntity.getUserId());

        param.put("corpid", corpid);
        param.put("del", 0);
        //合同主负责人
        param.put("isMain", 1);
        param.put("userIdIn", userIdIn);

        List<ContractUserEntity> contractUserList = contractUserModel.findEntitys(param);

        Set<Long> contractIdIn = new HashSet<>();
        for (ContractUserEntity entity : contractUserList) {
            contractIdIn.add(entity.getDataId());
        }
        List<PaymentEntityExt> paymentList;
        try {
            Integer nowTime = DateUtil.getTodayInt();
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                    .filter(termsQuery("data." + PaymentEnum.STATUS.getAttr(), Arrays.asList(PaymentStatusEnum.UN_RECEIVABLES.getCode(), PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())))
                    .filter(termsQuery("data." + PaymentEnum.CONTRACT.getAttr(), contractIdIn))
                    .filter(rangeQuery("data." + PaymentEnum.ESTIMATE_TIME.getAttr()).gte(nowTime).lt(nowTime + 7 * 86400));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            param.clear();
            param.put("corpid", corpid);
            param.put("del", 0);
            param.put("idIn", ids);
            paymentList = paymentModel.findEntitys(param);

        } catch (Exception e) {
            Long startTime = DateTimeUtil.getTodayInt();
            Long endTime = startTime + 7 * 86400;
            paymentList = paymentModel.getPaymentRemindByContractId(corpid, new ArrayList<>(contractIdIn), startTime, endTime);
        }

        Integer unPaymentCount = paymentList.size();
        long appId = 0;
        long menuId = 0;
        List<Long> ids = new ArrayList<>();
        //未回款金额
        Double unPaymentMoney = 0.0;
        for(PaymentEntityExt paymentEntity : paymentList){
            if(paymentEntity != null){
                JSONObject paymentObject = paymentEntity.getData();
                if (paymentObject != null) {
                    if (paymentObject.getDouble(PaymentEnum.UN_AMOUNT.getAttr()) != null) {
                        unPaymentMoney += paymentObject.getDouble(PaymentEnum.UN_AMOUNT.getAttr());
                    }
                    appId = paymentEntity.getAppId();
                    menuId = paymentEntity.getMenuId();
                    ids.add(paymentEntity.getId());
                }
            }
        }
        JSONObject jsonObject = null;
        if(unPaymentCount > 0){
            //没有回款信息不推送
            unPaymentMoney = (unPaymentMoney < 0) ? 0 : unPaymentMoney;

            jsonObject = new JSONObject();
            jsonObject.put("content", String.format(I18nMessageUtil.getMessage(I18nStringConstant.PAYMENT_REMIND_CONTENT), unPaymentCount, unPaymentMoney));
            jsonObject.put("title", String.format(I18nMessageUtil.getMessage(I18nStringConstant.RECEIVABLE_DAY), 7));
            jsonObject.put("appId", appId);
            jsonObject.put("menuId", menuId);
            jsonObject.put("dataIds", ids);
//            jsonObject.put("text", "销帮帮CRM七天收款提醒");
//            String messageUrl = proBaseConfig.getProjectDingtalkUrl() + String.format(DingtalkPageUrlEnum.PAYMENT_LIST.getUrl(), "");
//            jsonObject.put("messageUrl", messageUrl);
        }
        return jsonObject;
    }

    /**
     * 保存用户的销售简报推送
     *
     * @param userEntity 公司员工
     * @param pushTime 推送时间
     * @param dayStartTime 统计日/周开始时间--销售简报
     * @param dayEndTime 统计日/周结束时间--销售简报
     * @since 3.11
     * @author 焕勇
     * 创建时间：很久以前
     * 修改时间：2017-8-11 下午3:10:50
     */
    private void saveSalesPresentations(UserEntity userEntity, Long pushTime, Long dayStartTime, Long dayEndTime) {
        pushTime = getPushTime(pushTime);
        String corpid = userEntity.getCorpid();
        List<String> userIdList = new ArrayList<>();
        userIdList.add(userEntity.getUserId());

        JSONObject dataJson = getSalesPresentations(userEntity, dayStartTime, dayEndTime);
        if(dataJson == null){
            return ;
        }
        List<Long> refIdList = new ArrayList<>();
        refIdList.add(0L);

        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO();
        messageRabbitMqDTO.setCorpid(corpid);
        messageRabbitMqDTO.setUserIds(userIdList);
        messageRabbitMqDTO.setRefIds(refIdList);
        messageRabbitMqDTO.setRemind(0);
        messageRabbitMqDTO.setPushTime(pushTime);
        messageRabbitMqDTO.setTitle(dataJson.getString("title"));
        messageRabbitMqDTO.setContent("");
        List<OA.Body.Form> forms = new ArrayList<>();
//        dataJson.remove("text");
        dataJson.remove("title");
        Set<Map.Entry<String, Object>> set = dataJson.entrySet();
        for (Map.Entry<String, Object> entry : set) {
            OA.Body.Form form = new OA.Body.Form();
            form.setKey(entry.getKey());
            form.setValue(entry.getValue().toString());
            forms.add(form);
        }
        messageRabbitMqDTO.setForm(forms);

        PushRefTypePojo.Options options = new PushRefTypePojo.Options();
        options.setStart(dataJson.getLong("start"));
        options.setEnd(dataJson.getLong("end"));
        messageRabbitMqDTO.setOptions(options);

        try {
            messageService.insertPushData(messageRabbitMqDTO, PushTypeEnum.SALE_REPORT_PUSH);
        } catch (XbbException e) {
            LOG.warn("PushDataThread.saveSalesPresentations  insertPushData失败，corpid= " + corpid + ", message= " + messageRabbitMqDTO.toString(), e);
        }

    }

    /**
     * Description:
     * @param userEntity
     * @param dayStartTime
     * @param dayEndTime
     * @return com.alibaba.fastjson.JSONObject
     * @throws
     * @author 魏荣杰
     * @date 2019/2/21 18:49
     * @since v1.0
     */
    private JSONObject getSalesPresentations(UserEntity userEntity, Long dayStartTime, Long dayEndTime) {
        String corpid = userEntity.getCorpid();

        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("userId", userEntity.getUserId());
        param.put("del", 0);
        param.put("startTime", dayStartTime);
        param.put("endTime", dayEndTime);
        param.put("start", 0);
        param.put("pageNum", 1);
        List<TargetLogEntity> logList = targetLogModel.findEntitys(param);
        if (logList == null || logList.size() == 0) {
            //指标记录表内无该员工数据，则不用推送
            return null;
        }
        TargetLogEntity targetLogEntity = logList.get(0);

        String dateStr = DateTimeUtil.getDateStringEpochSecond(dayStartTime);
        if (dayEndTime - dayStartTime > 86400) {
            //周报
            dateStr = dateStr + "-" + DateTimeUtil.getDateStringEpochSecond(dayEndTime - 86400);
        }

		 /** 拼装推送格式
		 * {
			    "text": "销帮帮CRM销售简报",
			    "title": "2017-08-11简报",
			    "合同数据：": "签约合同数0、签约合同金额￥100.0",
			    "客户数据：": "新增客户数1、新增合同客户数0、新增机会客户数0",
			    "机会数据：": "新增机会数0、新增机会金额￥0.0、赢单机会数0",
			    "资金数据：": "已回款金额￥0.0、应收未收款￥0.0"
			}*/
        JSONObject jsonObject = new JSONObject(true);
        //头部标题
//        jsonObject.put("text", "销帮帮CRM销售简报");
        //正文标题
        jsonObject.put("title", dateStr + I18nMessageUtil.getMessage(CommonConstant.BRIEFING));
        //封入开始结束时间，页面跳转时用到
        jsonObject.put("start", dayStartTime);
        jsonObject.put("end", dayEndTime);

        CompanyConfigEntity companyConfigEntity = companyConfigModel.getConfigEntity(corpid, CompanyConfigEnum.REPORT_TARGETSET.getAlias());
        String configValue = (companyConfigEntity == null) ? "" : companyConfigEntity.getConfigValue();
        //模块名--该模块内的指标
        Map<String, List<ReportTargetEnum>> nameEnumMap = ReportTargetEnum.getTopEnumList(configValue);
        for (Map.Entry<String, List<ReportTargetEnum>> entry : nameEnumMap.entrySet()) {
            String name = entry.getKey();
            List<ReportTargetEnum> enumList = entry.getValue();
            String value = "";
            for (ReportTargetEnum reportTargetEnum : enumList) {
                if (!StringUtil.isEmpty(value)) {
                    value += "、";
                }
                //指标中文名
                String targetName = reportTargetEnum.getName();
                //指标英文名，与targetLogEntity内属性名一致，用于得到对应的指标值
                String alias = reportTargetEnum.getAlias();
                //1 Double，2 Integer
                Integer type = reportTargetEnum.getType();
                String unit = reportTargetEnum.getUnit();
                String prefix = Objects.equals(unit, I18nMessageUtil.getMessage(TabConstant.YUAN)) ? "￥": "";

                value += targetName + prefix;

                //得到的格式为：{“day”:0,”month”:0}
                String attr = (String) ReflectHelper.valueGet(targetLogEntity, alias);
                if (StringUtil.isEmpty(attr)) {
                    value += "0";
                }else {
                    JSONObject targetObject = JSONObject.parseObject(attr);
                    if (type == 1) {
                        Double amount = targetObject.getDouble("day");

                        //金额格式处理
                        value += StringUtil.formatDouble(amount, 2, 1);
                    }else {
                        value += targetObject.get("day");
                    }
                }
            }
            jsonObject.put(name + "：", value);
        }
        return jsonObject;
    }

    /**
     * 获取推送时间
     * @param pushTime	推送时间点
     * @return Integer 推送时间
     */
    private static Long getPushTime(Long pushTime) {

        pushTime = DateTimeUtil.getTodayInt()+pushTime;

        return pushTime;
    }
}
